using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Autowired.Core;
using CoreHelper;
using CoreHelper.Mapper;
using Loogn.OrmLite;
using Microsoft.IdentityModel.Tokens;
using project.api.Models;
using project.dao;
using project.dao.Models;

namespace project.api.Services
{
    [AppService]
    public class SysService
    {
        [Autowired] private SysRole_ResDao sysRoleResDao;
        [Autowired] private SysRoleDao sysRoleDao;
        [Autowired] private SysUserDao sysUserDao;
        [Autowired] private SysUser_ResDao sysUserResDao;
        [Autowired] private SysUser_RoleDao sysUserRoleDao;
        [Autowired] private SysResDao sysResDao;
        [Autowired] private AppSettings appSettings;

        public SysService(AutowiredService autowiredService)
        {
            autowiredService.Autowired(this);
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject<SysLoginResponse> SysLogin(SysLoginRequest request)
        {
            var md5Password = EncryptHelper.MD5Encrypt(request.Password);
            var user = sysUserDao.SingleWhere(DictBuilder
                .Assign("Account", request.Account).Assign("Password", md5Password));
            if (user == null)
            {
                return new ResultObject<SysLoginResponse>("账号或密码错误");
            }

            if (user.Status != 1)
            {
                return new ResultObject<SysLoginResponse>("账号已禁用");
            }

            var dict = new Dictionary<string, string>();
            dict.Add("userid", user.Id.ToString());

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Jwt.SigningKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: appSettings.Jwt.Issuer,
                audience: appSettings.Jwt.Audience,
                claims: dict.Select(x => new Claim(x.Key, x.Value)),
                expires: DateTime.Now.AddDays(1),
                signingCredentials: creds);
            var jwt = new JwtSecurityTokenHandler().WriteToken(token);

            return new ResultObject<SysLoginResponse>(new SysLoginResponse()
            {
                Jwt = jwt,
                UserInfo = SimpleMapper.Map<SysUserInfo>(user)
            });
        }


        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject EditUser(SysEditUserRequest request)
        {
            var user = SimpleMapper.Map<SysUser>(request);
            var flag = 0L;
            if (user.Id > 0)
            {
                flag = sysUserDao.Update(user,
                    "Name", "Gender", "Status", "Avatar");
            }
            else
            {
                if (sysUserDao.CountWhere("Account", user.Account) > 0)
                {
                    return new ResultObject("账号已存在");
                }

                user.Password = EncryptHelper.MD5Encrypt(user.Password);
                flag = sysUserDao.Insert(user);
            }

            return new ResultObject(flag);
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject SysResetPassword(SysResetPasswordRequest request)
        {
            if (string.IsNullOrEmpty(request.NewPassword))
            {
                return new ResultObject("密码不能为空");
            }

            var pwd = EncryptHelper.MD5Encrypt(request.NewPassword);
            var flag = sysUserDao.UpdateFieldById("Password", pwd, request.Id);
            return new ResultObject(flag);
        }

        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject<SysUserListResponse> SysUserList(SysUserListRequest request)
        {
            StringBuilder sb = new StringBuilder("1=1");
            var kw = SqlInjection.Filter(request.Keyword);
            if (!string.IsNullOrEmpty(kw))
            {
                sb.AppendFormat(" and Name like '%{0}%'", kw);
            }

            var plist = sysUserDao.SelectPage(new OrmLitePageFactor()
            {
                Conditions = sb.ToString(),
                PageIndex = request.PageIndex,
                PageSize = request.PageSize,
                OrderBy = "Id desc",
            });
            var response = new SysUserListResponse()
            {
                List = plist.List,
                PageCount = plist.PageCount,
                TotalCount = plist.TotalCount,
                HasMore = plist.PageIndex < plist.PageCount
            };
            return new ResultObject<SysUserListResponse>(response);
        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject UpdatePassword(SysUpdatePasswordRequest request)
        {
            var userid = request.GetUserId();
            var emp = sysUserDao.SingleById(userid);
            var oldPassword = EncryptHelper.MD5Encrypt(request.OldPassword);
            if (oldPassword != emp.Password)
            {
                return new ResultObject("原密码不正确");
            }

            var newPasword = EncryptHelper.MD5Encrypt(request.NewPassword);
            var flag = sysUserDao.UpdateFieldById("Password", newPasword, emp.Id);
            return new ResultObject(flag > 0);
        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject SysDeleteUser(SysIdRequest request)
        {
            var flag = sysUserDao.DeleteById(request.Id);
            if (flag > 0)
            {
                sysUserRoleDao.DeleteWhere("SysUserId", request.Id);
                sysUserResDao.DeleteWhere("SysUserId", request.Id);
            }

            return new ResultObject(flag);
        }


        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject<SysMenuDataResponse> SysMenuData(SysMenuDataRequest request)
        {
            var userid = request.GetUserId();
            var resIds = sysUserDao.GetUserResources(userid);
            var resList = sysResDao.SelectByIds(resIds);
            var response = new SysMenuDataResponse();
            //填充树形菜单数据
            var allList = resList.Where(x => x.Type == 1 && x.Status == 1)
                .OrderBy(x => x.OrderNum)
                .ThenBy(x => x.Id)
                .ToList();
            response.Menus = new List<SysResInfo>();
            ListToTree(response.Menus, allList, 0);

            return new ResultObject<SysMenuDataResponse>(response);
        }

        private void ListToTree(List<SysResInfo> targetTree, List<SysRes> allData, long parentId)
        {
            foreach (var sysRes in allData.Where(x => x.ParentId == parentId))
            {
                var info = SimpleMapper.Map<SysResInfo>(sysRes);
                if (allData.Any(x => x.ParentId == info.Id))
                {
                    info.Children = new List<SysResInfo>();
                    ListToTree(info.Children, allData, info.Id);
                }

                targetTree.Add(info);
            }
        }


        /// <summary>
        /// 编辑菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject SysEditRes(SysEditResRequest request)
        {
            var m = SimpleMapper.Map<SysRes>(request);

            var flag = 0L;
            if (request.Id > 0)
            {
                flag = sysResDao.Update(m);
            }
            else
            {
                flag = sysResDao.Insert(m);
            }

            return new ResultObject(flag);
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResultObject SysDeleteRes(SysIdRequest request)
        {
            var flag = sysResDao.DeleteById(request.Id);
            if (flag > 0)
            {
                sysRoleResDao.DeleteWhere("SysResId", request.Id);
                sysUserResDao.DeleteWhere("SysResId", request.Id);
            }

            return new ResultObject(flag);
        }

        //菜单列表
    }
}